#include "../code/server.hpp"
int pos = 0;

EventLoop base_loop;
LoopThreadPool thread_pool(&base_loop);



void CloseHeadler(Channel* channel)
{
    std::cout << "close fd " << channel->GetFd() << std::endl;

    channel->Remove();
    // close(channel->GetFd())    
    // delete channel;
}

void readHeadler(Channel* channel)
{
    int fd = channel->GetFd();
    char buf[1024] = { 0 };
    ssize_t ret = recv(fd, buf, sizeof(buf) - 1, 0);
    if(ret < 0)
    {
        CloseHeadler(channel);
        std::cout << "recv error" << std::endl;
        return;
    }
    else if(ret == 0)
    {
        CloseHeadler(channel);
        std::cout << "读到文件末尾关闭文件描述符" << std::endl;
        return;
    }
    buf[ret] = '\0';
    std::cout << buf << std::endl;
    channel->EnableWrite();
}

void WriteHeadler(Channel* channel)
{
    int fd = channel->GetFd();
    std::string buf = "hello muduo" + std::to_string(++pos);
    ssize_t ret = send(fd, buf.c_str(), buf.size(), 0);
    if(ret < 0)
    {
        CloseHeadler(channel);
        std::cout << "send error" << std::endl;
        return;
    }
    channel->DisableWrite();
}



void ErrorHeadler(Channel* channel)
{
    CloseHeadler(channel);
    std::cout << "处理错误" << std::endl;
}


void EventHeadler(EventLoop* loop, Channel* channel, uint64_t timerid)
{
    std::cout << "来了一个任务";
    loop->TimerRefresh(timerid);
}


std::unordered_map<int, PtrConnection> conns;

void ConnectCallBack(const PtrConnection& conn)
{
    LOG(Info, "链接创建成功 %p", conn.get());
}

void MessageCallBack(const PtrConnection& conn, Buffer* buf)
{
    LOG(Info, "%s", buf->ReadPos());
    buf->MoveReadOffset(buf->ReadableSize());
    std::string str = "hello muduo";
    // std::cout << "***********" << std::endl;
    conn->Send(str.c_str(), str.size());
    //conn->Shutdown();
}

void CloseCallback(const PtrConnection& conn)
{
    conns.erase(conn->GetId());
}

void AnyCallback(const PtrConnection& conn)
{
    // LOG(Info, "来了一个任务");
}



// 链接管理器
void Newconnection(int fd)
{
    static int id = 0;
    // int fd = lis_channel->GetFd();
    // int newfd = accept(fd, nullptr, nullptr);
    // if(newfd < 0)
    // {
    //     std::cout << "accept error" << std::endl;
    //     return;
    // }

    //uint64_t timerid = rand() % 10000;

    PtrConnection conn(new Connection(thread_pool.GetNextLoop(), fd, id));
    conn->SetConnectCallback(std::bind(ConnectCallBack, std::placeholders::_1));
    conn->SetMessageCallback(std::bind(MessageCallBack, std::placeholders::_1, std::placeholders::_2));
    conn->SetClosedCallback(std::bind(CloseCallback, std::placeholders::_1));
    conn->SetAnyEventCallback(bind(AnyCallback, std::placeholders::_1));
    // 启动非活跃超时销毁
    conn->EnableInactiveRelease(15);
    // 就绪初始化
    conn->Established();

    conns.insert(std::make_pair(id, conn));

    id++;
}

int main()
{

    srand(time(NULL));
    // Socket listen_sock;
    // listen_sock.CreateServer(8080);
    // Channel lis(&loop, listen_sock.GetFd());

    // // 回调中 获取新链接，为新链接创建channel并添加监控
    // lis.EnableRead();
    // lis.SetReadCallback(std::bind(Accepter, &loop, &lis));
    Acceptor acceptor(&base_loop, 8080);
    acceptor.SetAcceptCallback(std::bind(Newconnection, std::placeholders::_1));
    acceptor.Listen();

    thread_pool.SetThreadCount(3);
    thread_pool.Create();

    while(1)
    {
        base_loop.Start();
    }
    
    // Socket server;
    // server.CreateServer(8080);
    
    // while(1)
    // {
    //     int fd = server.Accept();
    //     Socket response(fd);
        
    //     char recv[1024];

    //     int ret = response.Recv(recv, 1023, 0);
    //     if(ret > 0)
    //     {
    //         recv[ret] = '\0';
    //         std::cout << recv << std::endl;
    //     }

        
    //     std::string rsp(recv);
    //     rsp = "server response : " + rsp;

    //     response.Send(rsp.c_str(), rsp.size(), 0);

    // }
    

    return 0;
}